<template>
    <mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :up="{use: false}" :down="{bgColor: 'transparent'}">
        <view class="dashboard">
            <!-- 顶部统计卡片 - 重新调整核销按钮位置 -->
            <view class="hero-card">
                <view class="hero-card-bg">
                    <view class="bg-decoration"></view>
                </view>
                <view class="card-content">
                    <view class="greeting-section">
                        <view class="greeting-text">
                            <text class="greeting">您好，</text>
                            <text class="merchant-name">{{pagesData.shop_name || '店主'}}</text>
                        </view>
                        <text class="current-time">{{time}}</text>
                    </view>
                    
                    <view class="quick-stats">
                        <view class="stat-item" v-for="(item, index) in todayObj" :key="index">
                            <text class="stat-value">{{item.val}}</text>
                            <text class="stat-label">{{item.name}}</text>
                        </view>
                    </view>
                    
                    <!-- 核销按钮放在卡片内底部 -->
                    <navigator url="/pages/jointoperation_order/jointoperation_order" hover-class="none" class="verify-nav">
                        <button class="verify-button pulse-effect">
                            <text class="button-icon iconfont icon-saoma"></text>
                            <text class="button-text">扫码核销</text>
                        </button>
                    </navigator>
                </view>
            </view>
            
            <!-- 订单数据卡片 - 改进版 -->
            <view class="metrics-container">
                <view class="metrics-header">
                    <text class="metrics-title">订单数据</text>
                    <navigator url="/pages/order/order" hover-class="none" class="view-more">
                        查看更多 <text class="iconfont icon-arrow-right"></text>
                    </navigator>
                </view>
                <view class="metrics-grid">
                    <view class="metric-card" v-for="(item, index) in orderObj" :key="index">
                        <view class="metric-icon-wrapper">
                            <text class="metric-icon iconfont" :class="getOrderIcon(index)"></text>
                        </view>
                        <view class="metric-info">
                            <text class="metric-value">{{item.val}}</text>
                            <text class="metric-label">{{item.name}}</text>
                        </view>
                    </view>
                </view>
            </view>
            
            <!-- 营业趋势图表 - 增强版 -->
            <view class="data-trend-card">
                <view class="trend-header">
                    <text class="trend-title">营业趋势</text>
                    <view class="period-tabs">
                        <text class="period-tab" :class="{'active': activePeriod === 'week'}" @click="changePeriod('week')">周</text>
                        <text class="period-tab" :class="{'active': activePeriod === 'month'}" @click="changePeriod('month')">月</text>
                        <text class="period-tab" :class="{'active': activePeriod === 'year'}" @click="changePeriod('year')">年</text>
                    </view>
                </view>
                
                <!-- 图表容器 -->
                <view class="chart-container" :class="{'loading': isLoading}">
                    <!-- 图表显示 -->
                    <view v-if="!isLoading && chartReady" class="chart-wrapper">
                        <qiun-data-charts 
                            type="mix"
                            :canvas2d="true"
                            :chartData="safeChartData" 
                            :opts="enhancedChartOpts"
                            :tooltipFormat="'tooltipCustom'"
                            canvasId="businessTrendChart"
                        />
                    </view>
                    
                    <!-- 无数据状态 -->
                    <view v-if="!isLoading && (!trendData.dates || trendData.dates.length === 0)" class="empty-data">
                        <view class="empty-icon iconfont icon-empty-data"></view>
                        <text class="empty-text">暂无营业数据</text>
                        <text class="empty-hint">完成一笔交易即可生成趋势图表</text>
                    </view>
                    
                    <!-- 加载中遮罩 -->
                    <view class="loading-overlay" v-if="isLoading">
                        <view class="spinner"></view>
                        <text class="loading-text">加载中...</text>
                    </view>
                </view>
                
                <!-- 自定义图例 -->
                <view class="custom-legend">
                    <view class="legend-item">
                        <view class="legend-marker income"></view>
                        <text class="legend-text">营业额</text>
                    </view>
                    <view class="legend-item">
                        <view class="legend-marker visits"></view>
                        <text class="legend-text">访问量</text>
                    </view>
                </view>
            </view>
            
            <!-- 快捷功能卡片 - 新增 -->
            <view class="quick-actions-card">
                <view class="quick-actions-title">快捷功能</view>
                <view class="quick-actions-grid">
                    <navigator url="/pages/statistics/statistics" hover-class="none" class="action-item">
                        <view class="action-icon-wrapper blue">
                            <text class="action-icon iconfont icon-data"></text>
                        </view>
                        <text class="action-text">营业统计</text>
                    </navigator>
                    <navigator url="/pages/goods/goods" hover-class="none" class="action-item">
                        <view class="action-icon-wrapper green">
                            <text class="action-icon iconfont icon-goods"></text>
                        </view>
                        <text class="action-text">商品管理</text>
                    </navigator>
                    <navigator url="/pages/order/order" hover-class="none" class="action-item">
                        <view class="action-icon-wrapper orange">
                            <text class="action-icon iconfont icon-order"></text>
                        </view>
                        <text class="action-text">订单查询</text>
                    </navigator>
                    <navigator url="/pages/setting/setting" hover-class="none" class="action-item">
                        <view class="action-icon-wrapper purple">
                            <text class="action-icon iconfont icon-settings"></text>
                        </view>
                        <text class="action-text">店铺设置</text>
                    </navigator>
                </view>
            </view>
        </view>
    </mescroll-body>
</template>

<script>
    import {
        apiIndex
    } from '@/api/store'

    import {
        apiVisit
    } from '@/api/app'
    import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins";
    export default {
        mixins: [MescrollMixin],
        data() {
            return {
                pagesData: {},
                loading: true,
                activePeriod: 'week',
                time: '',
                isLoading: false,
                chartReady: false,
                trendData: {
                    dates: [],
                    income: [],
                    visits: []
                },
                
                // 今日数据和订单数据
                todayObj: [{
                    name: '今日营业额',
                    val: '0.00'
                },
                {
                    name: '今日核销订单',
                    val: '0'
                },
                {
                    name: '今日进店人数',
                    val: '0'
                }],
                
                orderObj: [{
                    name: '自提订单',
                    val: '0'
                },
                {
                    name: '待核销',
                    val: '0'
                },
                {
                    name: '已核销',
                    val: '0'
                }],
                
                // 图表配置
                chartConfig: {
                    type: "mix",
                    canvasId: "mix-chart",
                    background: "#FFFFFF",
                    animation: true,
                    timing: "easeOut",
                    categories: [],
                    series: [],
                    xAxis: {
                        disableGrid: true,
                        itemCount: 7,
                        scrollShow: false
                    },
                    yAxis: {
                        data: [
                            {
                                min: 0,
                                format: "val",
                                fontSize: 11,
                                color: "#71767E"
                            },
                            {
                                min: 0,
                                format: "val",
                                fontSize: 11,
                                color: "#71767E"
                            }
                        ]
                    },
                    dataLabel: false,
                    width: 0,
                    height: 0,
                    extra: {
                        mix: {
                            column: {
                                width: 20,
                                radius: 6,
                                linearType: 'custom',
                                customColor: [
                                    {linearColor: ['#FF9500', '#FFBD38']}
                                ]
                            },
                            line: {
                                type: "curve",
                                width: 3,
                                linearType: 'custom',
                                customColor: [
                                    {linearColor: ['#4DA6FF', '#7FC2FF']}
                                ]
                            }
                        },
                        tooltip: {
                            showBox: true,
                            showArrow: true,
                            borderWidth: 0,
                            borderRadius: 4,
                            borderColor: '#FFFFFF',
                            backgroundColor: 'rgba(0,0,0,0.7)',
                            fontColor: '#FFFFFF',
                            fontSize: 13,
                            legendShow: false,
                            format: 'tooltipCustom'
                        }
                    }
                },
                
                // 增强版图表配置
                enhancedChartOpts: {
                    color: ["#FF9500", "#4DA6FF"],
                    padding: [15, 15, 0, 5],
                    enableScroll: false,
                    legend: {
                        show: false
                    },
                    xAxis: {
                        disableGrid: true,
                        fontColor: "#999999",
                        fontSize: 12
                    },
                    yAxis: {
                        gridType: "dash",
                        gridColor: "rgba(220,220,220,0.5)",
                        dashLength: 4,
                        data: [{
                            min: 0,
                            fontColor: "#999999",
                            fontSize: 12,
                            tofix: 0
                        }]
                    },
                    extra: {
                        mix: {
                            column: {
                                width: 20,
                                radius: 6,
                                linearType: 'custom',
                                customColor: [
                                    {linearColor: ['#FF9500', '#FFBD38']}
                                ]
                            },
                            line: {
                                type: "curve",
                                width: 3,
                                linearType: 'custom',
                                customColor: [
                                    {linearColor: ['#4DA6FF', '#7FC2FF']}
                                ]
                            }
                        },
                        tooltip: {
                            showBox: true,
                            showArrow: true,
                            borderWidth: 0,
                            borderRadius: 4,
                            borderColor: '#FFFFFF',
                            backgroundColor: 'rgba(0,0,0,0.7)',
                            fontColor: '#FFFFFF',
                            fontSize: 13,
                            legendShow: false
                        }
                    }
                }
            }
        },
        computed: {
            safeChartData() {
                // 确保图表数据有效
                if (!this.trendData.dates || this.trendData.dates.length === 0) {
                    return {
                        categories: [],
                        series: []
                    }
                }
                
                return {
                    categories: this.trendData.dates,
                    series: [
                        {
                            name: "营业额",
                            data: this.trendData.income,
                            type: "column"
                        },
                        {
                            name: "访问量",
                            data: this.trendData.visits,
                            type: "line"
                        }
                    ]
                }
            }
        },
        methods: {
            // 下拉刷新回调
            async downCallback() {
                await this.getPageInfo()
                this.mescroll.endSuccess()
            },
            
            // 上拉加载回调
            upCallback() {
                this.mescroll.endSuccess()
            },
            
            // 初始化滚动插件
            mescrollInit(mescroll) {
                this.mescroll = mescroll
            },
            
            // 获取页面数据
            async getPageInfo() {
                this.isLoading = true
                try {
                    const res = await apiIndex()
                    if (res) {
                        // 更新今日数据
                        this.todayObj[0].val = res.order_amount || '0.00'
                        this.todayObj[1].val = res.order_num || '0'
                        this.todayObj[2].val = res.shop_user || '0'
                        
                        // 更新订单数据
                        this.orderObj[0].val = res.self_order || '0'
                        this.orderObj[1].val = res.is_verification || '0'
                        this.orderObj[2].val = res.no_verification || '0'
                        
                        // 更新趋势图数据
                        this.trendData = {
                            dates: res.dates || [],
                            income: res.echarts_order_amount || [],
                            visits: res.echarts_user_visit || []
                        }
                        
                        // 更新店铺信息
                        this.pagesData = res
                        
                        // 标记图表准备就绪
                        this.chartReady = true
                    }
                } catch (error) {
                    console.error('获取数据失败:', error)
                    uni.showToast({
                        title: '数据加载失败',
                        icon: 'none'
                    })
                } finally {
                    this.isLoading = false
                }
            },
            
            // 切换时间周期
            changePeriod(period) {
                this.activePeriod = period
                // 这里可以根据选择的周期调用不同的API或传递不同参数
                this.getChartData(period)
            },
            
            // 根据周期获取图表数据
            getChartData(period) {
                this.isLoading = true
                // 模拟不同周期的数据加载
                setTimeout(() => {
                    // 实际应用中应该调用API获取不同周期的数据
                    this.isLoading = false
                }, 800)
            },
            
            // 获取订单图标
            getOrderIcon(index) {
                const icons = ['icon-pickup', 'icon-pending', 'icon-verified']
                return icons[index] || 'icon-order'
            },
            
            // 显示当前时间
            showTime() {
                var d = new Date()
                var year = d.getFullYear()
                var month = d.getMonth() + 1
                var date = d.getDate()
                
                var hour = Number(d.getHours()) <= 9 ? '0' + Number(d.getHours()) : Number(d.getHours())
                var min = Number(d.getMinutes()) <= 9 ? '0' + Number(d.getMinutes()) : Number(d.getMinutes())
                var sec = Number(d.getSeconds()) <= 9 ? '0' + Number(d.getSeconds()) : Number(d.getSeconds())
                
                var str = year + '-' + month + '-' + date + "  " + hour + ":" + min + ":" + sec
                this.time = str
            }
        },
        onLoad() {
            // 初始化数据
            this.getPageInfo()
            
            // 设置时间更新
            setInterval(this.showTime, 1000)
        }
    }
</script>

<style lang="scss">
/* 全新的配色方案 */
.dashboard {
    background-color: #F8F9FC;
    min-height: 100vh;
    padding-bottom: 30rpx;
}

.hero-card {
    position: relative;
    background: #FFFFFF;
    border-radius: 20rpx;
    margin: 30rpx;
    padding-bottom: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
    overflow: hidden;
    
    .hero-card-bg {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 1;
        
        .bg-decoration {
            position: absolute;
            right: -40rpx;
            top: -50rpx;
            width: 250rpx;
            height: 250rpx;
            border-radius: 125rpx;
            background: linear-gradient(135deg, rgba(255, 149, 0, 0.1), rgba(255, 184, 80, 0.3));
        }
    }
}

.card-content {
    position: relative;
    z-index: 2;
    padding: 30rpx;
}

.greeting-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .greeting-text {
        .greeting {
            font-size: 28rpx;
            color: #71767E;
        }
        
        .merchant-name {
            font-size: 36rpx;
            font-weight: bold;
            color: #2D3142;
        }
    }
    
    .current-time {
        font-size: 24rpx;
        color: #71767E;
    }
}

.quick-stats {
    display: flex;
    justify-content: space-between;
    margin-top: 20rpx;
    
    .stat-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .stat-value {
            font-size: 40rpx;
            font-weight: bold;
            color: #FF9500;
            margin-bottom: 10rpx;
        }
        
        .stat-label {
            font-size: 24rpx;
            color: #71767E;
        }
    }
}

.verify-nav {
    margin-top: 30rpx;
    display: flex;
    justify-content: center;
}

.verify-button {
    width: 90%;
    background: linear-gradient(135deg, #FF9500, #FFBD38);
    border: none;
    border-radius: 40rpx;
    padding: 20rpx 0;
    box-shadow: 0 8rpx 16rpx rgba(255, 149, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    
    .button-icon {
        font-size: 36rpx;
        color: #FFFFFF;
        margin-right: 12rpx;
    }
    
    .button-text {
        font-size: 32rpx;
        color: #FFFFFF;
        font-weight: 500;
    }
}

.pulse-effect {
    animation: pulse 2s infinite;
}

/* 订单数据卡片 */
.metrics-container {
    background: #FFFFFF;
    border-radius: 20rpx;
    margin: 30rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.metrics-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .metrics-title {
        font-size: 30rpx;
        font-weight: bold;
        color: #2D3142;
    }
    
    .view-more {
        font-size: 24rpx;
        color: #71767E;
        
        .icon-arrow-right {
            font-size: 24rpx;
        }
    }
}

.metrics-grid {
    display: flex;
    justify-content: space-between;
    
    .metric-card {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20rpx 10rpx;
        
        .metric-icon-wrapper {
            width: 80rpx;
            height: 80rpx;
            border-radius: 40rpx;
            background-color: rgba(255, 149, 0, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 16rpx;
            
            .metric-icon {
                font-size: 40rpx;
                color: #FF9500;
            }
        }
        
        .metric-info {
            display: flex;
            flex-direction: column;
            align-items: center;
            
            .metric-value {
                font-size: 36rpx;
                font-weight: bold;
                color: #FF9500;
                margin-bottom: 8rpx;
            }
            
            .metric-label {
                font-size: 24rpx;
                color: #71767E;
            }
        }
    }
}

/* 营业趋势图表 */
.data-trend-card {
    background: #FFFFFF;
    border-radius: 20rpx;
    margin: 30rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.trend-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .trend-title {
        font-size: 30rpx;
        font-weight: bold;
        color: #2D3142;
    }
    
    .period-tabs {
        display: flex;
        
        .period-tab {
            font-size: 24rpx;
            color: #71767E;
            padding: 10rpx 20rpx;
            border-radius: 30rpx;
            margin-left: 10rpx;
            
            &.active {
                color: #FFFFFF;
                background: linear-gradient(135deg, #FF9500, #FFBD38);
            }
        }
    }
}

.chart-container {
    height: 400rpx;
    position: relative;
    
    &.loading {
        opacity: 0.7;
    }
    
    .chart-wrapper {
        height: 100%;
    }
    
    .empty-data {
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        
        .empty-icon {
            font-size: 80rpx;
            color: #D8D8D8;
            margin-bottom: 20rpx;
        }
        
        .empty-text {
            font-size: 28rpx;
            color: #2D3142;
            margin-bottom: 10rpx;
        }
        
        .empty-hint {
            font-size: 24rpx;
            color: #71767E;
        }
    }
    
    .loading-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(255, 255, 255, 0.8);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        
        .spinner {
            width: 60rpx;
            height: 60rpx;
            border: 4rpx solid rgba(255, 149, 0, 0.3);
            border-radius: 50%;
            border-top-color: #FF9500;
            animation: spin 1s linear infinite;
            margin-bottom: 16rpx;
        }
        
        .loading-text {
            font-size: 24rpx;
            color: #71767E;
        }
    }
}

.custom-legend {
    display: flex;
    justify-content: center;
    margin-top: 20rpx;
    
    .legend-item {
        display: flex;
        align-items: center;
        margin: 0 20rpx;
        
        .legend-marker {
            width: 24rpx;
            height: 12rpx;
            border-radius: 6rpx;
            margin-right: 8rpx;
            
            &.income {
                background: linear-gradient(to right, #FF9500, #FFBD38);
            }
            
            &.visits {
                background: linear-gradient(to right, #4DA6FF, #7FC2FF);
            }
        }
        
        .legend-text {
            font-size: 24rpx;
            color: #71767E;
        }
    }
}

/* 快捷功能卡片 */
.quick-actions-card {
    background: #FFFFFF;
    border-radius: 20rpx;
    margin: 30rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.quick-actions-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #2D3142;
    margin-bottom: 30rpx;
}

.quick-actions-grid {
    display: flex;
    justify-content: space-between;
    
    .action-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .action-icon-wrapper {
            width: 100rpx;
            height: 100rpx;
            border-radius: 50rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 16rpx;
            transition: transform 0.2s;
            
            &.blue {
                background-color: rgba(77, 166, 255, 0.1);
                
                .action-icon {
                    color: #4DA6FF;
                }
            }
            
            &.green {
                background-color: rgba(76, 217, 100, 0.1);
                
                .action-icon {
                    color: #4CD964;
                }
            }
            
            &.orange {
                background-color: rgba(255, 149, 0, 0.1);
                
                .action-icon {
                    color: #FF9500;
                }
            }
            
            &.purple {
                background-color: rgba(175, 82, 222, 0.1);
                
                .action-icon {
                    color: #AF52DE;
                }
            }
            
            .action-icon {
                font-size: 48rpx;
            }
        }
        
        .action-text {
            font-size: 26rpx;
            color: #2D3142;
        }
        
        &:active {
            .action-icon-wrapper {
                transform: scale(0.95);
            }
        }
    }
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
</style>
